<?php
declare(strict_types=1);
/**
 * +----------------------------------------------------------------------
 * | 栏目控制制器
 * +----------------------------------------------------------------------
 */

namespace app\controller\sys;

// 引入框架内置类
use think\facade\View;

use app\model\Category as CategoryModel;
use app\utils\ReUtils;

class Category extends Base
{
    public function index()
    {
        $list = CategoryModel::getList(['order'=>'id ASC']);

        $list = list_tree($list, 'id', 'parent_id');

        View::assign('list', $list);

        View::assign('types', ['一般','目录','单页/链接/锚点']);

        return View::fetch();
    }

    /**
     * 新增 or 修改
     * @param int $id  info id 
     * @return mix 
     */
    public function save($id = 0)
    {
        if ($this->app->request->isPost()) {
            $params = $this->app->request->param();

            if ($params['name'] == '') {
                $this->error("名称不能为空");
            }

            try {
                $id = $params['id'];
                unset($params['id']);

                if ($id != 0) {
                    CategoryModel::update($params, ['id' => $id]);
                } else {
                    CategoryModel::create($params);
                }
            } catch (\Exception $e) {
                $msg = $e->getMessage();

                $this->error("错误提示:" . $msg);
            }
            $this->success('操作成功', (string)url('index'));
        } else {
            if ($id != 0) {
                $data = CategoryModel::find($id);
            } else {
                $data = new CategoryModel();
                $data->is_nav = 1;
            }
    
            View::assign('data', $data);
    
            $list = CategoryModel::getParentList();
    
            View::assign('list', $list);
    
            return View::fetch();
        }
    }

    // 删除
    public function delete($id)
    {
        if ($this->app->request->isPost()) {
            if (CategoryModel::where('parent_id', $id)->value('id')) {
                return ReUtils::error('子栏目不为空, 若要删除请先清空子栏目');
            }

            if (CategoryModel::destroy($id)) {
                return ReUtils::success();
            } else {
                return ReUtils::error();
            }
        }
    }

    // 导航状态变更
    public function navStatus(int $id)
    {
        if ($this->app->request->isPost()) {
            return CategoryModel::navStaus($id);
        }
    }
}
